package com.xilihui.xlh.business.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.weigan.loopview.LoopView;
import com.xilihui.xlh.R;
import com.xilihui.xlh.business.dialogs.AddressPickerDialog;
import com.xilihui.xlh.business.dialogs.DatePickerDialog;
import com.xilihui.xlh.business.dialogs.PickerViewDialog;
import com.xilihui.xlh.business.entities.AreaEntity;
import com.xilihui.xlh.business.entities.ItemsEntity;
import com.xilihui.xlh.business.entities.UploadingEntity;
import com.xilihui.xlh.business.requests.SignedRequest;
import com.xilihui.xlh.business.widget.CircleImageView;
import com.xilihui.xlh.component.ipicker.IPicker;
import com.xilihui.xlh.constant.UrlConst;
import com.xilihui.xlh.core.app.BaseCompatActivity;
import com.xilihui.xlh.core.app.BaseEntity;
import com.xilihui.xlh.core.glide.ImageHelper;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.SPUtil;
import com.xilihui.xlh.core.util.TimeFormatUtil;
import com.xilihui.xlh.core.util.ToastUtil;
import com.xilihui.xlh.core.util.YEventBuses;

import org.feezu.liuli.timeselector.Utils.TextUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.http.Query;

/**
 * Created by Administrator on 2018/5/17.
 */

public class ApplyActivity extends BaseCompatActivity implements View.OnClickListener, IPicker.OnSelectedListener {
    
    @BindView(R.id.ll_headImage)
    LinearLayout ll_headImage;
    @BindView(R.id.ll_name)
    LinearLayout ll_name;
    @BindView(R.id.ll_sex)
    LinearLayout ll_sex;
    @BindView(R.id.ll_year)
    LinearLayout ll_year;
    @BindView(R.id.ll_annual)
    LinearLayout ll_annual;
    @BindView(R.id.ll_address)
    LinearLayout ll_address;
    @BindView(R.id.ll_identity)
    LinearLayout ll_identity;
    @BindView(R.id.sdv_head)
    SimpleDraweeView sdv;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.tv_sex)
    TextView tv_sex;
    @BindView(R.id.tv_year)
    TextView tv_year;
    @BindView(R.id.tv_annual)
    TextView tv_annual;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.et_identity)
    EditText et_identity;
    @BindView(R.id.iv_zhengmian)
    ImageView iv_zhengmian;
    @BindView(R.id.iv_fangmian)
    ImageView iv_fangmian;
    @BindView(R.id.iv_shouchi)
    ImageView iv_shouchi;
    @BindView(R.id.checkbox)
    CheckBox checkBox;
    @BindView(R.id.tv_submit)
    TextView tv_submit;
    @BindView(R.id.tv_protocol)
    TextView tv_protocol;
    
    private int type = 0;

    private long endTime = System.currentTimeMillis() / 1000;// 日期
    
    String head_pic = "";
    String read_name = "";
    String sex = "";
    String birthday = "";
    String working_age = "";
    
    private String address = "";
    private String mProvinceId = "";
    private String mCityId = "";
    private String mCountyId = "";
    
    String idcard = "";
    String idcard_img_hand = "";
    String idcard_img_back = "";
    String idcard_img_front = "";
    
    @Override
    public int getLayout() {
        return R.layout.activity_apply;
    }

    @Override
    public String initTitle() {
        return "签约申请";
    }

    @Override
    public void initUI(@Nullable Bundle savedInstanceState) {
        ll_headImage.setOnClickListener(this);
        ll_year.setOnClickListener(this);
        ll_sex.setOnClickListener(this);
        ll_annual.setOnClickListener(this);
        ll_address.setOnClickListener(this);
        iv_zhengmian.setOnClickListener(this);
        iv_fangmian.setOnClickListener(this);
        iv_shouchi.setOnClickListener(this);
        tv_submit.setOnClickListener(this);
        tv_protocol.setOnClickListener(this);
    }

    @Override
    public void initData() {
        
    }
    
    
    public void selectIdentity(){
        
        ArrayList<String> data = new ArrayList<>();
        for (int i=0;i<21;i++){
            data.add(i+"年");
        }
        data.add("20年以上");
        LogUtil.i("mylog","data:");
        new PickerViewDialog<String>(this,data,0){

            @Override
            protected void setItems(LoopView loopView, List<String> list) {
                loopView.setItems(list);
            }

            @Override
            protected void onConfirm(String s, int position) {
                tv_annual.setText(s);
                if(s.equals("20年以上")){
                    working_age = "21";
                }else {
                    working_age = s.substring(0,s.length()-1);
                }
            }
        }.show();
        
    }
    
    public void selectSex(){
        
        ArrayList<String> data = new ArrayList<>();
        data.add("男");
        data.add("女");

        new PickerViewDialog<String>(this,data,0) {
            @Override
            protected void setItems(LoopView loopView, List<String> list) {
                loopView.setItems(list);
            }

            @Override
            protected void onConfirm(String s, int position) {
                tv_sex.setText(s);
                if(s.equals("男")){
                    sex = "1";
                }else{
                    sex = "2";
                }
            }
        }.show();
        
    }

    public void selectAddress(){
        
        AreaEntity areaEntity = (AreaEntity)SPUtil.getObject(SPUtil.ADDRESS);
        if(areaEntity!=null){
            AddressPickerDialog addressPickerDialog = new AddressPickerDialog(this);
            addressPickerDialog.setCallback(new AddressPickerDialog.Callback() {
                @Override
                public void onSelected(String province, String city, String county, String provinceId, String cityId, String countyId) {
                    address = province +" "+city + " "+county;
                    mProvinceId = provinceId;
                    mCityId = cityId;
                    mCountyId = countyId;
                    tv_address.setText(address);
                }
            });

            addressPickerDialog.setData(areaEntity);
            addressPickerDialog.show();
        }else {
            address();
        }


    }
    
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ll_headImage:
                showSelectImage(1);
                break;
            case R.id.ll_sex:
                selectSex();
                break;
            case R.id.ll_year:
                new DatePickerDialog(this)
                        .setCurrentDate(endTime)
                        .setMinimalDate(1920,01,01)
                        .setCallback(new DatePickerDialog.Callback() {
                            @Override
                            public void onSelected(int year, int month, int day) {
                                endTime = TimeFormatUtil.toMillis(year + "-" + month + "-" + day);
                                tv_year.setText(year+"-"+timeHandle((month))+"-"+timeHandle(day));
                                birthday = endTime+"";
                            }
                        }).show();
                break;
            case R.id.ll_annual:
                selectIdentity();
                break;
            case R.id.ll_address:
                selectAddress();
                break;
            case R.id.iv_zhengmian:
                //身份正面
                LogUtil.i("mylog","zhengmian");
                showSelectImage(2);
                break;
            case R.id.iv_fangmian:
                //身份反面
                showSelectImage(3);
                break;
            case R.id.iv_shouchi:
                //手持身份证
                showSelectImage(4);
                break;
            case R.id.tv_submit:
                submit();
                break;
            case R.id.tv_protocol:
                Intent intent = new Intent(ApplyActivity.this, WebActivity.class);
                intent.putExtra("type",2);
                startActivity(intent);
                break;
                
        }
        
    }
    
    public void showSelectImage(int type){
        this.type = type;
        IPicker iPicker = IPicker.getInstance();
        iPicker.setLimit(1);
        iPicker.setCropEnable(true);
        iPicker.setOnSelectedListener(this);
        iPicker.open(this);
    }

    @Override
    public void onSelected(List<String> paths) {
        upload(type,paths.get(0));
    }
    
    public void upload(final int type, String url){
        SignedRequest.uploadImgAndCompress(this,url)
                .compose(DoTransform.<UploadingEntity>applyScheduler(this,true))
                .compose(ApplyActivity.this.<UploadingEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<UploadingEntity>(this) {
                    @Override
                    protected void onSuccess(UploadingEntity entity) {
                        ToastUtil.toastShortPositive(entity.getMsg());
                        switch (type){
                            case 1:
                                head_pic = entity.getImg_url();
                                String url = UrlConst.baseUrl() +head_pic;
                                sdv.setImageURI(url);
                                LogUtil.i("mylog","head_pic"+UrlConst.baseUrl()+head_pic);
                                break;
                            case 2:
                                idcard_img_hand = entity.getImg_url();
                                ImageHelper.display(ApplyActivity.this,iv_zhengmian, UrlConst.baseUrl()+
                                idcard_img_hand);
                                break;
                            case 3:
                                idcard_img_back = entity.getImg_url();
                                ImageHelper.display(ApplyActivity.this,iv_fangmian,UrlConst.baseUrl()+
                                idcard_img_back);
                                break;
                            case 4:
                                idcard_img_front = entity.getImg_url();                                
                                ImageHelper.display(ApplyActivity.this,iv_shouchi,UrlConst.baseUrl()+
                                idcard_img_front);
                                break;
                        }
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortPositive(msg);
                    }
                });
    }
    
    public void address(){
        
        SignedRequest.getAddress(this)
                .compose(DoTransform.<AreaEntity>applyScheduler(this,true))
                .compose(ApplyActivity.this.<AreaEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<AreaEntity>(this) {
                    @Override
                    protected void onSuccess(AreaEntity entity) {
                        AddressPickerDialog addressPickerDialog = new AddressPickerDialog(ApplyActivity.this);
                        addressPickerDialog.setCallback(new AddressPickerDialog.Callback() {
                            @Override
                            public void onSelected(String province, String city, String county, String provinceId, String cityId, String countyId) {
                                address = province +" "+city + " "+county;
                                mProvinceId = provinceId;
                                mCityId = cityId;
                                mCountyId = countyId;
                                tv_address.setText(address);
                            }
                        });

                        addressPickerDialog.setData(entity);
                        addressPickerDialog.show();
                        SPUtil.putObject(SPUtil.ADDRESS,entity);
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortNegative(msg);
                    }
                });
        
    }
    
    public String timeHandle(int num){
        String str = "";
        if(num<10){
            str = "0" + num;
        }else {
            str = num + "";
        }
        return str;
    }
    
    public void submit(){
        
        if(TextUtil.isEmpty(head_pic)){
            ToastUtil.toastShortNegative("请上传工作照");
            return;
        }
        
        read_name = et_name.getText().toString().trim();
        if(TextUtil.isEmpty(read_name)){
            ToastUtil.toastShortNegative("请输入真实姓名");
            return;
        }
        
        if(TextUtil.isEmpty(sex)){
            ToastUtil.toastShortNegative("请选择性别");
            return;
        }
        
        if(TextUtil.isEmpty(birthday)){
            ToastUtil.toastShortNegative("请选择出生年月");
            return;
        }
        
        if(TextUtil.isEmpty(working_age)){
            ToastUtil.toastShortNegative("请选择行业年薪");
            return;
        }
        
        if(TextUtil.isEmpty(mProvinceId)){
            ToastUtil.toastShortNegative("请选择所在地址");
            return;
        }
        
        idcard = et_identity.getText().toString().trim();
        if(TextUtil.isEmpty(idcard)){
            ToastUtil.toastShortNegative("请输入身份证号码");
            return;
        }
        
        if(TextUtil.isEmpty(idcard_img_hand)){
            ToastUtil.toastShortNegative("请上传身份证正面");
            return;
        }
        
        if(TextUtil.isEmpty(idcard_img_back)){
            ToastUtil.toastShortNegative("请上传身份证反面");
            return;
        }
        
        if(TextUtil.isEmpty(idcard_img_front)){
            ToastUtil.toastShortNegative("请上传手持身份证");
            return;
        }
        
        if(!checkBox.isChecked()){
            ToastUtil.toastShortNegative("请先同意服务协议");
            return;
        }
        
        SignedRequest.submit(ApplyActivity.this,head_pic,read_name,sex,birthday,working_age,
                mProvinceId,mCityId,mCountyId,idcard,idcard_img_hand,idcard_img_back,idcard_img_front)
                .compose(DoTransform.<BaseEntity>applyScheduler(ApplyActivity.this,true))
                .compose(ApplyActivity.this.<BaseEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<BaseEntity>(this) {
                    @Override
                    protected void onSuccess(BaseEntity entity) {
                        ToastUtil.toastShortPositive(entity.getMsg());
                        YEventBuses.post(new YEventBuses.Event("login_"));
                        finish();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortNegative(msg);
                    }
                });
        
        
        
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
